<?php

namespace App\Console\Commands\Swoole;

use SwooleTW\Http\Commands\HttpServerCommand;
use Swoole\Process;

class Http extends HttpServerCommand
{

    protected $signature = 'swoole:http {action : start|stop|restart|reload|infos} {--hot}';

    protected $description = '启动swoole http服务';

    //进程名称
    protected $process_name =  'swoole hot reload';
    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $pid_path = base_path('storage/logs/swoole_hot_reload.pid');
        $watch_path =  base_path('watch/index.js');
        $base_path =  base_path();
        if ($this->argument('action') === 'start' && $this->option('hot') ) {
            if(!is_dir(base_path('node_modules')))  shell_exec("/usr/local/node/bin/npm install ".$base_path);
               $process =  new \Swoole\Process(function (\Swoole\Process $worker) use ( $watch_path  ) {
               $worker->exec("/usr/local/node/bin/node",[$watch_path]);
            });
            $process->name($this->process_name);
            $process->start();
            $this->closeReload($pid_path); //关闭现有的reload
            /**
             *  把pid写入内部文件夹
             */
            $myfile = fopen($pid_path, "w");
            fwrite($myfile, $process->pid);
            fclose($myfile);
            /* */

        } else if ($this->argument('action') === 'stop' ) {
            //停止热重载功能
            $this->closeReload($pid_path);
        }
        parent::handle();
    }


    public function closeReload(string $pid_path){
        if( file_exists($pid_path)){
            try {
                $pid =  file_get_contents($pid_path);
                shell_exec('kill '.$pid);
                unlink($pid_path);  //删除pid文件
            } catch (\Exception $e) {
                echo 'stop hot reload error ' . $e->getMessage();
            }
        }

    }
}
